import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import java.io.File;

import org.htmlparser.Parser;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.HtmlPage;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 

public class AttackVectorTester {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		//TODO: read cheatsheet XML file. Fetch <code> element and create a page that includes this text 
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder;
		ScriptExtractor2 scr = null;
		Parser parser = null;
		Lexer lexer = null;
		String htmlPage = null;
		Node vectorNode = null;
		Vector<ScriptNode> sn = null;
		
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse (new File("xssAttacks.xml"));
			doc.getDocumentElement ().normalize ();
			NodeList listOfVectors = (NodeList) doc.getElementsByTagName("code");
			int totalVectors = listOfVectors.getLength();
			System.out.println("Total no of vectors : " + totalVectors);

			for(int s=0; s<listOfVectors.getLength() ; s++){

				vectorNode = listOfVectors.item(s);
				System.out.println("\r\n"+(s+1)+") "+ vectorNode.getTextContent());
				htmlPage = "<HTML>\r\n<HEAD>\r\n</HEAD>\r\n<BODY>\r\n" + 
					vectorNode.getTextContent() + "\r\n</BODY></HTML>";
				lexer = new Lexer(htmlPage);
				parser = new Parser(lexer);
				scr = new ScriptExtractor2(parser);
				sn = scr.getScriptNodes();
				for (ScriptNode n : sn ){
					System.out.println("Attack Payload");
					if (n.IsExternal())
						System.out.println(n.getSource());
					else
						System.out.println(n.getOrigCode());
				}

			}//end of for loop with s var

		} catch (ParserConfigurationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DetectorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
